using System;
using System.Collections.Generic;
using System.Linq;
using Amazon.SimpleNotificationService;
using Amazon.SimpleNotificationService.Model;

namespace ShuttleBus.Transports.AmazonSqs.Clients
{
    public class SnsWrapper : ISnsClient
    {
        private readonly AmazonSimpleNotificationService _sns;

        public SnsWrapper(AmazonSimpleNotificationService sns)
        {
            _sns = sns;
        }

        public void Subscribe(string queueArn, IEnumerable<Topic> topics)
        {
            foreach (var topic in topics)
            {
                var subscribeRequest = new SubscribeRequest()
                    .WithProtocol("SQS")
                    .WithEndpoint(queueArn)
                    .WithTopicArn(topic.TopicArn);

                _sns.Subscribe(subscribeRequest);
            }  
        }

        public Topic Create(string name)
        {
            var response = _sns.CreateTopic(new CreateTopicRequest { Name = name });
            return new Topic {TopicArn = response.CreateTopicResult.TopicArn};
        }

        public IEnumerable<Topic> QueryTopics(string name)
        {
            var listTopicsRequest = new ListTopicsRequest();
            var response = _sns.ListTopics(listTopicsRequest);

            var results = response.ListTopicsResult.Topics;

            return results.Where(t =>
            {
                var topicArn = t.TopicArn;
                var topicName = topicArn.Substring(topicArn.LastIndexOf(':') + 1);
                return StringsAreEqual(topicName, name);
            });
        }

        public IEnumerable<Subscription> QuerySubscriptions(string name)
        {
            var listSubscriptionsRequest = new ListSubscriptionsRequest();
            var response = _sns.ListSubscriptions(listSubscriptionsRequest);

            var results = response.ListSubscriptionsResult.Subscriptions;
            return results
                .Where(s =>
                           {
                               var topicArn = s.TopicArn;
                               var topicName = topicArn.Substring(topicArn.LastIndexOf(':') + 1);
                               return StringsAreEqual(topicName, name) && s.Protocol == "sqs";
                           });
        }

        private static bool StringsAreEqual(string potentialMatch, string nameToMatch)
        {
            return string.Compare(potentialMatch, nameToMatch, StringComparison.CurrentCultureIgnoreCase) == 0;
        }

    }
}